<!-- 维护参考区间 -->
<script setup lang='ts' name="ReferenceRange">
import {reactive, ref, onMounted, watch, onActivated} from 'vue'
import {HeaderData} from '@/components/dTable/dTable'
import {OperButton, SearchFromItem, SearchButton} from '@/components/dTable/dHeader'
import {PageConfig, defaultPage, defaultPageSize, defaultPageSizes, defaultLayout} from '@/components/dTable/dFooter'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import pageContainer from '@/components/pageContainer.vue'
import operation from '@/components//dTable/components/operation.vue'
import popUp  from './popup.vue'
import { ElMessage, ElMessageBox, FormRules} from 'element-plus'
import { inspectItemListCanKao, referenceRangeList, referenceRangeDelete } from '@/api/instrument/Inspection'
import { ColorTheme, ColorRed } from '@/api/config'
import {useRoute} from 'vue-router'
const route = useRoute()
// 左侧表格筛选条件
const searchData = ref<any>({
  instrumentId:'',
  keywords:''
})

// 右侧表格筛选条件
const searchItemData = ref<any>({
  instrumentId:'', //
  itemId:''
})

//默认选中
const defualtSeleted = ref<any>(undefined)

// 操作栏
const operationData = [
  {code:'edit', label:'编辑', iconConfig:{icon:'common-edit', type:'custom', color:ColorTheme, size:20}},
  {code:'del', label:'删除', iconConfig:{icon:'common-delete', type:'custom', color:ColorRed, size:20}}
]

//数据
const tableData = ref<any>([])
//数据
const tableData2 = ref<any>([])

// 弹窗显示
const popShow = ref(false)

// 弹窗显示
const maintainShow = ref(false)

// 弹窗查询id
const itemId = ref('0')

// 新增仪器id
const addId = ref('0')

//
const inspectResultType = ref('0')

// 试剂下拉数据
const reagentSelete = ref<Array<any>>([{value:'', label:'全部'}])

//表格数据
const tableHeaderData = ref<Array<HeaderData>>([
  {prop:'itemCode', label:'检验项目编码', columnType:'text', align:'center', 'min-width':'100'},
  {prop:'itemName', label:'检验项目名称', columnType:'text', align:'center', 'min-width':'100'}
])
//表格数据
const tableHeaderData2 = ref<Array<HeaderData>>([
  {prop:'genderName', label:'适用性别', columnType:'text', align:'center', 'min-width':'100'},
  {prop:'ageRange', label:'年龄范围', columnType:'text', align:'center', 'min-width':'100'},
  {prop:'referenceRange', label:'参考区间', columnType:'text', align:'center', 'min-width':'100'},
  {prop:'viewRange', label:'参考区间描述', columnType:'text', align:'center', 'min-width':'120'},
  {prop:'reviewRangeHigh', label:'高复查值', columnType:'text', align:'center', 'min-width':'100'},
  {prop:'reviewRangeLow', label:'低复查值', columnType:'text', align:'center', 'min-width':'100'},
  {prop:'dangerHigh', label:'高危值', columnType:'text', align:'center', 'min-width':'80'},
  {prop:'dangerRangeLow', label:'低危值', columnType:'text', align:'center', 'min-width':'80'},
  {prop:'operation', label:'操作', columnType:'slot', align:'center', 'min-width':'70'}
])

//数据
const formData = ref<any>({
  instrumentId:'',
  reagentId:'', // 功能名称
  resultType:'', // 功能分类
  sampleType:'', //	所属菜单
  gender:'', // 功能名称
  ageRangeLow:null, // 年龄范围
  ageRangeHigh:0, //	年龄范围
  ageRangeUnit:'1', // 岁、周、年 单位
  normalRangeLow:0, // 参考区间
  normalRangeHigh:0, //	参考区间
  reviewRangeLow:0, // 低复查值
  reviewRangeHigh:0, // 高复查值
  dangerRangeLow:'', //	低危值
  dangerRangeHigh:'', // 高危值
  dangerPositive:'', // 功能分类
  viewRange:'', // 参考区间描述
  inspectItemId:''
})

//底部
const pageConfig = ref<PageConfig>({
  currentPage:defaultPage,
  pageSize:defaultPageSize,
  pageSizes:defaultPageSizes,
  total:0,
  disabled:false,
  layout:defaultLayout
})

//表头
const operButtons = ref<Array<OperButton>>([
  {label:'新增', type:'noraml', iconConfig:{icon:'common-add', type:'custom', color:'#fff'}, code:'add'}
])
// 筛选区功能
const searchFromItems = ref<Array<SearchFromItem>>(
  [
    {label:'检验项目', placeholder:'请输入检验项目', type:'input', prop:'keywords', enterSubmit:true}
  ]
)

const searchFromData = reactive<any>({keywords:''})

const searchFromRules = reactive<FormRules>({
  keywords:[
    {required:false, message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']}
  ],
  itemCode:[
    {required:false, message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']}
  ]
})


// 筛选区功能
const searchFromItems2 = ref<Array<SearchFromItem>>(
  // [
  //   {label:'试剂', placeholder:'请选择', type:'selete', prop:'reagentId', changeSubmit:true, seleteData:reagentSelete.value}
  // ]
)

const searchFromData2 = reactive<any>({reagentId:''})

const searchFromRules2 = reactive<FormRules>({
  antibioticGroupCode:[
    {required:false, message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']}
  ]
})

// 分页查询接口
const IfinspectItemList = (index?:number) => {
  inspectItemListCanKao(searchData.value).then(res => {
    if (res.data.code === 200) {
      tableData.value = res.data.data
      if (tableData.value.length === 0) {
        tableData2.value = []
      }
      // pageConfig.value.total = Number(res.data.total)
      if (index !== undefined && tableData.value[index]) {
        defualtSeleted.value = tableData.value[index]
      } else {
        defualtSeleted.value = undefined
      }
    }
  })
}



// 右侧列表刷新
const IfreferenceRangeList = (id?:string) => {
  if (id) {
    searchItemData.value.itemId = id
  }
  referenceRangeList(searchItemData.value).then(res => {
    res.data.data.map(item => {
      item.operation = operationData
    })
    tableData2.value = res.data.data
  })
}





// 删除接口
const IfantibioticRemove = (id:string) => {
  referenceRangeDelete({id:id}).then(res => {
    ElMessage({
      type: 'success',
      message: '操作成功'
    })
    IfreferenceRangeList(addId.value)
  })
}



// 左侧表格按钮搜索配置
const serachButtons = ref<Array<SearchButton>>([
  {type:'search'},
  {type:'clear'}
])
const onSubmit = () => {
  searchData.value.keywords  = searchFromData.keywords
  // searchData.value.itemCode  = searchFromData.itemCode
  IfinspectItemList(0)
}


// 右侧表格按钮搜索配置
const onSubmits = () => {
  searchItemData.value.reagentId  = searchFromData2.reagentId === '' ? null : searchFromData2.reagentId
  IfreferenceRangeList()
}

//排序回调
const onSotrChange = (obj) => {
  // console.log('排序', obj)
}

//单元格点击回调
const onCellClick = (row, col) => {
  // console.log('单元格', row, col)
}

//行点击回调
const onRowClick = (row) => {
  if (row === null) return
  addId.value = row.id
  inspectResultType.value = row.inspectResultType + ''
  IfreferenceRangeList(row.id)
}

//多选回调
const onMultipleSelection = (rows:Array<any>) => {
  // console.log('多选', rows)
}
//清除表单
const onFormClear = () => {
  searchData.value.keywords = ''
  // searchData.value.itemCode = ''
  IfinspectItemList(0)
}
//清除表单
const onFormClears = () => {
  // searchItemData.value.inspectItemId = ''
  searchItemData.value.reagentId = null
  IfreferenceRangeList()
}

const onSizeChange = () => {
  // searchData.value.limit = pageConfig.value.pageSize
  // IfinspectItemList()
}

const onCurrentChange = () => {
  // searchData.value.page = pageConfig.value.currentPage
  // IfinspectItemList()
}


const onOperation = (name:string) => {
  if (name === 'add') {
    formData.value = {
      instrumentId:'',
      reagentId:'', // 功能名称
      resultType:'', // 功能分类
      sampleType:'', //	所属菜单
      gender:'', // 功能名称
      ageRangeLow:null, // 年龄范围
      ageRangeHigh:null, //	年龄范围
      ageRangeUnit:'1', // 岁、周、年 单位
      normalRangeLow:null, // 参考区间
      normalRangeHigh:null, //	参考区间
      reviewRangeLow:null, // 低复查值
      reviewRangeHigh:null, // 高复查值
      dangerRangeLow:null, //	低危值
      dangerRangeHigh:null, // 高危值
      dangerPositive:'', // 功能分类
      viewRange:'', // 参考区间描述
      inspectItemId:''
    }
  }
  popShow.value = true
}


// 操作栏点击事件
const onErtion = (err, row) => {
  switch (err) {
  case 'del':
    ElMessageBox.confirm(
      '是否确认删除此参考区间？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(() => {
        IfantibioticRemove(row.id)
      })
      .catch(() => {
        // ElMessage({
        //   type: 'info',
        //   message: '取消'
        // })
      })
    break
  case 'edit':
    // 编辑


    row.dangerPositive = row.dangerPositive === 1 ? true : false
    formData.value = {...row}
    popShow.value = true
    break
  }


}
// 弹窗取消
const oncancel = () => {
  popShow.value = false
  IfreferenceRangeList()
}

// 弹窗关闭
const onclose = () => {
  popShow.value = false
  IfreferenceRangeList()
}

// 弹窗保存
const onconfirm = () => {
  // IfinspectItemList(0)
  IfreferenceRangeList(addId.value)
  popShow.value = false
}

// watch(
//   () => route.query,
//   () => {

//     const str = route.query ? route.query : {}
//     if (!route.query.id) return
//     // searchFromItems2.value.map(item => {
//     //   if (item.type === 'selete' && item.prop === 'reagentId') {
//     //     item.seleteData = []
//     //   }
//     // })
//     searchData.value.instrumentId = str.id
//     searchItemData.value.instrumentId = str.id
//     IfinspectItemList(0)
//   }
// )

// 生命周期
onMounted(() => {
  const str = route.query ? route.query : {}
  if (!route.query.id) return
  searchData.value.instrumentId = str.id
  searchItemData.value.instrumentId = str.id
  IfinspectItemList(0)
})
onActivated(() => {
  // IfinspectItemList(0)
  const str = route.query ? route.query : {}
  if (!route.query.id) return
  // searchFromItems2.value.map(item => {
  //   if (item.type === 'selete' && item.prop === 'reagentId') {
  //     item.seleteData = []
  //   }
  // })
  searchData.value.instrumentId = str.id
  searchItemData.value.instrumentId = str.id
  IfinspectItemList(0)
})
</script>

<template>
  <page-container>
    <div class="box">
      <div class="top" style="width: calc(1613px - 1076px);">
        <d-table-promote
          :search-form-items="searchFromItems"
          :search-buttons="serachButtons"
          :table-data="tableData"
          :table-header-data="tableHeaderData"
          :label-width="100"
          :search-from-justify="'flexStart'"
          :default-seleted="defualtSeleted"
          :search-form-data="searchFromData"
          :search-rules="searchFromRules"
          :page-config="pageConfig"
          :show-index="false"
          :show-footer="false"
          @form-submit="onSubmit"
          @sort-change="onSotrChange"
          @cell-click="onCellClick"
          @row-click="onRowClick"
          @multiple-selection="onMultipleSelection"
          @form-clear="onFormClear"
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
        />
      </div>
      <div class="line" />
      <div class="bottom" style="width: calc(100% - 580px);">
        <d-table-promote
          :oper-buttons="tableData.length===0?[]:operButtons"
          :search-form-items="searchFromItems2"
          :search-buttons="[]"
          :table-data="tableData2"
          :table-header-data="tableHeaderData2"
          :search-from-justify="'flexStart'"
          :search-form-data="searchFromData2"
          :search-rules="searchFromRules2"
          :show-footer="false"
          :force-show-button="true"
          :show-index="false"
          @operation="onOperation"
          @form-submit="onSubmits"
          @form-clear="onFormClears"
        >
          <template #operation="scope">
            <operation :row="scope.row" :col="scope.item" :force-show-button="true" @opertion-click="onErtion" />
          </template>
          <!-- <template #operbutton-append>
            <el-button type="primary" @click="onAdd">
              新增
            </el-button>
          </template> -->
        </d-table-promote>
      </div>
    </div>
  </page-container>
  <pop-up
    v-if="popShow"
    :show-dialog="popShow"
    :pop-data="formData"
    :pop-id="searchData.instrumentId"
    :add-id="addId"
    :inspect-result-type="inspectResultType"
    @cancel="oncancel"
    @close="onclose"
    @confirm="onconfirm"
  />
</template>

<style scoped lang="less">
.line{
  width: 6px;
  height: 100%;
  background: #F2F2F2;
}
.box  {
  height: 100%;
  flex: 1;
  justify-content: space-between;
  display: flex;

}

// .box .top{
//   height: 780px;
//   // height: calc(100%-85px);
// }
</style>